import LinkedList,{equalsType} from "../LinkedList";
import Node from "../Node";
import defaultEquals from "../../utils/defaultEquals";

export default class CircularLinkedList<T> extends LinkedList<T>{
    constructor(equalsFn:equalsType<T> = defaultEquals) {
        super(equalsFn);
    }

    insert(element: T, index: number) {
        let new_node: Node<T> = new Node();
        new_node.value = element;
        if (index > this.count) {
            throw new Error("下标越界")
        }
        let p_node: Node<T> | undefined = undefined;
        let n_node: Node<T> | undefined = undefined;
        if (index === 0) {
            new_node.next = this.head;
            if(!this.head){
                new_node.next = new_node;
            }else{
                (this.getElementAt(this.size()-1) as Node<T>).next = new_node;
            }
            this.head = new_node;
            return;
        }
        p_node = <Node<T>>this.getElementAt(index - 1);
        n_node = p_node.next;
        p_node.next = new_node;
        new_node.next = n_node;
        this.count++;
    }

    removeAt(index: number): T | undefined {
        if (this.isEmpty() || index >= this.count) {
            return undefined;
        }

        let now_node = this.getElementAt(index);
        let p_node = this.getElementAt(index - 1);
        let n_node = now_node?.next
        if (index === 0) {
            this.head = n_node;
            (this.getElementAt(this.size()-1) as Node<T>).next = this.head;
        }
        if (p_node) {
            p_node.next = n_node;
        }
        this.count--;
        return now_node?.value;
    }

}
